package com.UKIT.airtickets.Activities

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.UKIT.airtickets.Activities.fragments.AccountFragment
import com.UKIT.airtickets.Activities.fragments.FavouritesFragment
import com.UKIT.airtickets.Activities.fragments.MainFragment
import com.UKIT.airtickets.R
import com.UKIT.airtickets.Service.Handlers.LanguageHandler
import com.UKIT.airtickets.Service.SettingsApp
import com.UKIT.airtickets.databinding.ActivityMainBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private val languageHandler = LanguageHandler(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        CoroutineScope(Dispatchers.Main).launch {
            languageHandler.changeLanguage(SettingsApp.userId)
        }

        binding.bottomNavigation.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.avia_btn -> {
                    loadFragment(createFragment<MainFragment>())
                    true
                }
                R.id.like -> {
                    loadFragment(FavouritesFragment())
                    true
                }
                R.id.profile -> {
                    loadFragment(createFragment<AccountFragment>())
                    true
                }
                else -> false
            }
        }

        loadFragment(MainFragment())
    }

    private inline fun <reified T : Fragment> createFragment(): T {
        val fragmentClass = T::class.java
        return fragmentClass.getConstructor().newInstance().apply {
            arguments = Bundle()
        }
    }

    private fun loadFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }
}
